package com.csii.ams.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csii.adhoc.exception.ParamValidityException;
import com.csii.adhoc.id.UidGenerator;
import com.csii.adhoc.info.role.service.RoleService;
import com.csii.adhoc.info.user.UserPo;
import com.csii.adhoc.info.user.UserVo;
import com.csii.adhoc.info.user.service.UserService;
import com.csii.ams.ArchDef;
import com.csii.ams.BusiDef;
import com.csii.ams.SearchBean;
import com.csii.ams.SystemBusi;
import com.csii.ams.mapper.BusiDefMapper;
import com.csii.ams.mapper.SystemBusiMapper;
import com.csii.ams.service.BusiDefService;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @description:
 * @author: panChuanJiang
 * @create: 2021-03-18 09:28
 */
@Service("busiDefService")
public class BusiDefServiceImpl implements BusiDefService {
    @Resource
    private BusiDefMapper busiDefMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UidGenerator uidGenerator;
    @Value("${poc.ams.filehome}")
    private String filehome;
    @Autowired
    private RoleService roleService;
    @Resource
    private SystemBusiMapper systemBusiMapper;


    @Override
    public List<SystemBusi> selectAmsSystem() {
        return systemBusiMapper.selectAmsSystem();
    }

    @Override
    public List<SystemBusi> selectListSystemBusi(List<String> sys) {
        return systemBusiMapper.selectListSystemBusi(sys);
    }

    @Override
    public IPage<UserVo> searchUserByOrgId(SearchBean searchBean, Page<UserVo> page) {
        return busiDefMapper.searchUserByOrgId(searchBean,page);
    }

    @Override
    public void submitReview(BusiDef busiDef) {
        Map<String, String> map = busiDefMapper.queryReview(busiDef);
        if (map != null && map.size() > 0) {
            busiDefMapper.updateReview(busiDef);
        } else {
            busiDefMapper.submitReview(busiDef);
        }
    }

    @Override
    public void updateReview(BusiDef busiDef) {
        busiDefMapper.updateReview(busiDef);
    }

    @Override
    @Transactional
    public void insertBusiDef(BusiDef busiDef) {
        busiDef.setBusiCd(uidGenerator.getUID() + "");
        busiDefMapper.insertBusiDef(busiDef);
        busiDefMapper.insertListBusiArch(busiDef);
    }

    @Override
    @Transactional
    public void updateBusiDef(BusiDef busiDef) {
        busiDefMapper.updateBusiDef(busiDef);
        busiDefMapper.deleteBusiArch(busiDef.getBusiCd());
        busiDefMapper.insertListBusiArch(busiDef);
    }

    @Override
    public IPage<BusiDef> queryPageBusiDef(BusiDef busiDef, Page<BusiDef> page) {
        IPage<BusiDef> busiDefIPage = busiDefMapper.queryPageBusiDef(busiDef, page);
        for (BusiDef busi : busiDefIPage.getRecords()) {
            List<ArchDef> archDefs = busi.getArchDefs();
            if (archDefs != null && archDefs.size() > 0) {
                StringBuilder str = new StringBuilder();
                for (ArchDef def : archDefs) {
                    str.append(def.getArchNm()).append(",");
                }
                busi.setArchDefsStr(str.substring(0, str.length() - 1));
            }
        }
        return busiDefIPage;
    }

    @Override
    public List<BusiDef> queryListBusiDef(BusiDef busiDef) {
        List<BusiDef> busiDefs = busiDefMapper.queryListBusiDef(busiDef);
        for (BusiDef busi : busiDefs) {
            List<ArchDef> archDefs = busi.getArchDefs();
            if (archDefs != null && archDefs.size() > 0) {
                StringBuilder str = new StringBuilder();
                for (ArchDef def : archDefs) {
                    str.append(def.getArchNm()).append(",");
                }
                busi.setArchDefsStr(str.substring(0, str.length() - 1));
            }
        }
        return busiDefs;
    }

    @Override
    public void deleteBusiDef(String id) {
        busiDefMapper.deleteByPrimaryKey(id);
        busiDefMapper.deleteBusiArch(id);
    }

    @Override
    public Workbook queryDownLoadDetails(UserVo userVO,String busiCd) {
        //判断权限
        if (userVO.getName() != null && userVO.getPassword() != null) {
            UserPo userPo = userService.selectUserByUserName(userVO.getName());
            if (userPo == null) {
                throw new ParamValidityException("用户名错误:" + userVO.getName());
            }
            String inputPassword = userVO.getPassword();
            if (!inputPassword.equals(userPo.getPassword())) {
                throw new ParamValidityException("密码错误");
            }
            if (!userPo.getRole().contains("00010")) {//档案下载角色
                throw new ParamValidityException("没有此权限");
            }
        }
        BusiDef busiDef = busiDefMapper.selectByPrimaryKey(busiCd);
        List<ArchDef> archDefs = busiDef.getArchDefs();

        List<String> fieldList = new ArrayList<>();
        fieldList.add("姓名");
        for (ArchDef archDef : archDefs) {
            fieldList.add(archDef.getArchNm());//获取所有列
        }
        File dir = new File(filehome);
        File[] files = dir.listFiles();
        Map<String, List<ArchDef>> data = new HashMap<>();//用户名，用户对应的档案
        SearchBean searchBean = new SearchBean();
        searchBean.setSearchCriteria01(busiDef.getBusiInst());
        searchBean.setSearchCriteria02(busiDef.getBusiCd());
        searchBean.setSearchCriteria03(userVO.getApprovalStatus());
        List<UserVo> userVos = busiDefMapper.searchUserByOrgId(searchBean,new Page<>()).getRecords();
        Map<String, String> cartName = new HashMap<>();
        //初始化数据
        for (UserVo user : userVos) {
            List<ArchDef> archs = new ArrayList<>();
            for (ArchDef archDef : archDefs) {
                ArchDef arch = new ArchDef();
                arch.setExist(false);
                arch.setArchNm(archDef.getArchNm());
                arch.setArchCd(archDef.getArchCd());
                archs.add(arch);
            }
            cartName.put(user.getIdCard(), user.getName());
            data.put(user.getName(), archs);
        }
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    String archCd = file.getName();
                    File[] idCardFiles = file.listFiles();
                    for (File idCardFile : idCardFiles) {
                        if (idCardFile.isFile()) {
                            String name = idCardFile.getName();
                            String idCard = name.split("\\.")[0];
                            if (cartName.containsKey(idCard)) {
                                List<ArchDef> list = data.get(cartName.get(idCard));
                                for (ArchDef def : list) {
                                    if (def.getArchCd().equals(archCd)) {
                                        def.setExist(true);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return genExcelFile(data, fieldList, filehome, busiDef.getBusiNm());
    }


    private Workbook genExcelFile(Map<String, List<ArchDef>> data,
                              List<String> fieldList, String filePath, String fileName) {
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet(fileName);
        Row row1 = sheet.createRow(0);
        // 增加列信息
        for (int i = 0; i < fieldList.size(); i++) {
            String colChName = fieldList.get(i);
            Cell cell = row1.createCell(i);
            cell.setCellValue(colChName);
        }
        int rowNum = 1;
        for (Map.Entry<String, List<ArchDef>> entry : data.entrySet()) {
            List<ArchDef> value = entry.getValue();
            Row row = sheet.createRow(rowNum);
            for (int i = 0; i < value.size() + 1; i++) {
                String val;
                if (i == 0) {
                    val = entry.getKey();
                } else {
                    val = value.get(i - 1).getExist() ? "有" : "无";
                }
                Cell cell = row.createCell(i);
                cell.setCellValue(val);
            }
            rowNum++;
        }
        return workbook;
    }
}
